package org.jasig.cas.web;

import org.jasig.cas.web.myctrl.controller.KaptchaController;
import org.jasig.cas.web.dao.SystemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by catold on 16/2/25.
 */
public class LoadKaptchaFilter implements Filter {
    public static final String CODE_OPEN_STR = "isCodeOpen";
    private SystemDao systemDao;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 判断是否是登录验证
        String username = request.getParameter("username");

        if (username == null) {
            // 第一次载入页面判断是否设置验证码
            boolean result = systemDao.isKaptchaOpen();

            request.getSession().removeAttribute(CODE_OPEN_STR);
            request.getSession().setAttribute(CODE_OPEN_STR, result);
//                if (result) {
//                    Random rn = new Random();
//                    int answer = rn.nextInt(9000) + 1000;
//                    request.getSession().setAttribute("code", String.valueOf(answer));
//                } else {
//                    request.getSession().removeAttribute("code");
//                }
        } else {
            if((boolean)request.getSession().getAttribute(CODE_OPEN_STR)){
                // 验证登录,先验证验证码
                String code = (String) request.getSession().getAttribute(KaptchaController.RANDOMCODEKEY);
                if (code != null && !code.equals(request.getParameter("code"))) {
                    request.getSession().setAttribute("wrong", true);
                    request.getRequestDispatcher("/login").forward(request, response);
                }
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    public SystemDao getSystemDao() {
        return systemDao;
    }

    public void setSystemDao(SystemDao systemDao) {
        this.systemDao = systemDao;
    }

}
